package module::1_gucci_fr::default;
use Encode;
use vars qw($VERSION @ISA @EXPORT);
$VERSION = 1.00;
@ISA     = qw(Module::Module);
@EXPORT  = ();
use strict;

# ----------------------------------------------------
# constructor
# 11/22/2012 Louise create
# ----------------------------------------------------
sub new {
	my $class = shift;
	my %parm  = @_;
	my $this  = {};
	bless $this, $class;
	return $this;
}

# ----------------------------------------------------
# get all product's url and categories then write them
# into temp xml
# 11/22/2012 Louise create
# ----------------------------------------------------

sub filter {

	#A200000 Filter retailer website starts
	Log::Write::setLog('A200000');
	my $this     = shift;
	my $writexml = new Feed::XML();
	my $data     = $main::filedata;
	my $hostURL  = $this->{'config'}->{'host_url'};
	my $catalog  = { 'Product' => [] };
	my $charset  = 'utf-8';
	my $splitString = '<Split>';

	# get categoryUrls
	my @categoryUrls = &getCategoryUrls($hostURL, $charset, $splitString);
	#print "@categoryUrls";
	if ( !@categoryUrls ) {
		# E200000: filter failed
		Log::Write::setLog('E200000');
		return;
	}
	else {
		# A200003: The total count of the entryUrl obtained
		Log::Write::setLog( 'A200003', { 'COUNT' => scalar(@categoryUrls) } );
	}
	
	# get all product links
	my @allProducts = &getFilterProduct( $charset, \@categoryUrls, $splitString );
	
	# write tree date into XML file
	if (@allProducts) {
		$catalog->{'Product'} = \@allProducts;
		$writexml->addXML( $catalog, $this->{'config'}->{'data_filter_file'} );
		# A200002the total count of detail page urls
		Log::Write::setLog( 'A200002', { 'COUNT' => scalar(@allProducts) } );
	}
	else {
		# E200000filter failed
		Log::Write::setLog('E200000');
	}

	# A299999Filter retailer website end.
	Log::Write::setLog('A299999');
			
}
	
# ----------------------------------------------------
# parse all products detail page and write the infos
# into final XML feed
# 11/23/2012 Louise create
# ----------------------------------------------------
sub parser {

	# A300000Parser detail page starts.
	Log::Write::setLog('A300000');
	my $this = shift;

	# new parser object
	my $parserObj = module::1_gucci_fr::parser->new;

	# new $writexml object, used for read and write XML info
	my $writeXml = new Feed::XML();

	#read xml create by filter to get all products infos(url and category)
	my @xmlInfo = $writeXml->readXML( $this->{'config'}->{'data_filter_file'} );

	my $count = 0;
	my $total = 0;

	# $catalog is used for recording a set of products
	my $catalog = { 'Product' => [] };
	my $hostUrl = $this->{'config'}->{'host_url'};
	my $brand = 'Gucci';
	for my $oneTemp (@xmlInfo) {
		# %ProductInfo : one product info from *_filter.xml
		my %oneTempInfo = %{$oneTemp};
		my $productId   = ( @{ $oneTempInfo{'ProductId'} } )[0];
		my $url         = ( @{ $oneTempInfo{'ProductURL'} } )[0];
		my $name        = ( @{ $oneTempInfo{'Name'} } )[0];
		my %productInfo;
		eval {
			# get infos from product detail page and save it in hash variable
			%productInfo = $parserObj->parseAndgetInfo($url, $name);
		};
		if ($@) {
			# E300003 : Failed to extract information from XXX page.
			Log::Write::setLog( "E300003", { 'URL' => $url } );
			next;
		}
		if ( $productInfo{'Time'} ) {
			my $product = {
				'Retailer'    => $this->{'config'}->{'retailer_name'},
				'ProductId'   => $oneTempInfo{'ProductId'},
				'Name'        => $productInfo{'Name'},
				'Brand'       => $brand,
				'Price'       => $productInfo{'Price'},
				#'SalePrice'   => $productInfo{'SalePrice'},
				'Description' => $productInfo{'Description'},
				'ProductURL'  => $oneTempInfo{'ProductURL'},
				'ImageURL'    => $productInfo{'ImageURL'},
				'Category'    => $oneTempInfo{'Category'},
				'Size'        => $productInfo{'Size'},
				'Color'       => $productInfo{'Color'},
				#'InStock'     => $productInfo{'InStock'},
				'Time'        => $productInfo{'Time'}
			};

			$catalog->{'Product'} = [ @{ $catalog->{'Product'} }, $product ];

			$count++;
			$total++;

			# write data into XML per 100(configurable) records
			if ( $count == $this->{'config'}->{'write_frequency'} ) {
				$writeXml->addXML( $catalog,
					$this->{'config'}->{'data_feed_file'} );
				$catalog = { 'Product' => [] };

				# A300001 : Record XXX prodcuts have been appended to feed file.
				Log::Write::setLog( "A300001", { 'COUNT' => $count } );
				$count = 0;
			}
		}
	}
	$writeXml->addXML( $catalog, $this->{'config'}->{'data_feed_file'} );

	# A300001 : Record XXX prodcuts have been appended to feed file.
	Log::Write::setLog( "A300001", { 'COUNT' => $count } );

	if ($total) {
	   # A300003 : Record XXX prodcuts have been written into feed file totally.
		Log::Write::setLog( 'A300003', { 'COUNT' => $total } );
		# A399999 : Parser detail page end.
		Log::Write::setLog('A399999');
	}
	else {
		# E300000 : Parser failed.
		Log::Write::setLog('E300000');
	}
}

	
# ----------------------------------------------------
# get all category urls
# 11/22/2012 Louise create
# ----------------------------------------------------
sub getCategoryUrls {
	my $url     = shift;
	my $charset = shift;
	my $splitString = shift;
	my $data    = $main::filedata;
	my @categoryUrls;
	my $content = $data->getPage( $url, $charset );

	# get page failed
	if ( !$content ) {
		# E200001 Failed to get XX entrance information.
		Log::Write::setLog( 'E200001', { 'URL' => $url } );
		return;
	}
	else{
		$content =~ s/<!--.*?-->//isg;
	}
	
	if ( $content =~ /<div[^>]*class="[^"]*"[^>]*>(.*?)<nav[^>]*id="header_userbuyflow"[^>]*>/is ) {
		my $navText = $1;
		while ( $navText =~ /<span[^>]*class="mega_link[^"]*"[^>]*>([^<]*?)<\/span>\s*<div[^>]*class="mega_col[^"]*"[^>]*>(.*?)<li[^>]*class="mega_menu/isg ) {
			my $cat1Name = $1;
			my $subCatText = $2;
			$cat1Name =~ s/^\s+|\s+$//isg;
			
			while ( $subCatText =~ /<a[^>]*href="([^"]*)">([^<]*?)<\/a>[^<]*<\/li>/isg ) {
				my $cat2Url = $1;
				my $cat2Name = $2;
				
				push(@categoryUrls, $cat2Url.$splitString.$cat1Name.$splitString.$cat2Name);
#				print 	"@categoryUrls\n";
				
				my $thirdCatText = $main::filedata->getPage($cat2Url, $charset);
				while( $thirdCatText=~ /<a[^>]*href="([^"]*)"[^>]*class="(?:selected|category_nav_remote_link)">(.*?)<\/a>/isg ) {
					my $cat3Url = $1;
					my $cat3Name = $2;
					if ( $cat3Name ne 'Afficher tout'){
						push(@categoryUrls, $cat3Url.$splitString.$cat1Name.$splitString.$cat2Name.$splitString.$cat3Name);
					
#						print 	"@categoryUrls\n";
					}
				}
			}
		}
	}
	return @categoryUrls;
}

# ----------------------------------------------------
# get all entry urls
# 11/23/2012 Louise create
# ----------------------------------------------------
sub getFilterProduct {

	my $charset      = shift;
	my $entryUrls    = shift;
	my $splitString  = shift;

	my @entryUrlList = @{$entryUrls};
	my @allProducts;
	
	for my $entryUrlRef (@entryUrlList) {
		my ($url, @cats) = split($splitString, $entryUrlRef);
		my $content = $main::filedata->getPage($url, $charset);		
		# get page failed
		if ( !$content ) {
			# E200001 Failed to get XX entrance information.
			Log::Write::setLog( 'E200001', { 'URL2' => $url } );
			next;
		}
		else{
			$content =~ s/<!--.*?-->//isg;
		}
	
		if ( $content =~ /<div[^>]*id="panel_wrapper[^"]*"[^>]*>(.*)<div[^>]*id="container_quick_view[^"]*"[^>]*>/is ) {
			my $productContent = $1;
			$productContent =~ s/&quot;/"/isg;
			$productContent =~ s/&gt;/>/isg;
			$productContent =~ s/&lt;/</isg;
			my @tempArray;
			my $productURL;
			my $productName;
			my $productId;
			
			# common
			while ( $productContent =~ /<h3>\s*<a[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>\s*<\/h3>/isg ) {
				$productURL = $1;
				$productName = $2;
				$productId = substr($productURL, -15);		
								
				if(!$productURL){
					Log::Write::setLog( "E200008", { 'URL' => $url, 'POINT' => 'ProductURL' } );
					next;
				}
				if(!$productName){
					Log::Write::setLog( "E200008", { 'URL' => $url, 'POINT' => 'ProductName' } );
					next;
				}
				if(!$productId){
					Log::Write::setLog( "E200008", { 'URL' => $url, 'POINT' => 'ProductId' } );
					next;
				}
				my $product = {
					'ProductId'  => $productId,
					'ProductURL' => $productURL,
					'Name'       => $productName,
					'Category'   => [ { 'Part' => \@cats } ],
				};
				push @tempArray, $product;
			}
			
			# baby
			while ( $productContent =~ /<li[^>]*class="no_quickview[^"]*">.*?<a[^>]*href="([^"]*)"[^>]*>\s*<\/a>\s*<\/div>/isg ){
				my $product2URL = $1;
				my $product2Content = $main::filedata->getPage($product2URL, $charset);
				while ($product2Content =~ /<li[^>]*class="no_quickview">.*?(<a[^>]*href="(?:http:\/\/www.gucci.com)?\/fr\/styles\/[^"]*"><img[^>]*alt="[^"]*")/isg) {
					my $singleProductInfo = $1;
					if ($singleProductInfo =~ /<a[^>]*href="((?:http:\/\/www.gucci.com)?\/fr\/styles\/[^"]*)"></is ){
						$productURL = $1;
						if($productURL !~ /http:\/\//is){
							$productURL = 'http://www.gucci.com'.$productURL;
						}
					}
					if ($singleProductInfo =~ /<a[^>]*href="(?:http:\/\/www.gucci.com)?\/fr\/styles\/([^"]*)"></is ) {
						$productId = $1;
					}
					if ($singleProductInfo =~ /<a[^>]*href="(?:http:\/\/www.gucci.com)?\/fr\/styles\/[^"]*"><img[^>]*alt="([^"]*)"/is ) {
						$productName = $1;
					}
					
					if(!$productURL){
						Log::Write::setLog( "E200008", { 'URL' => $product2URL, 'POINT' => 'ProductURL' } );
						next;
					}
					if(!$productName){
						Log::Write::setLog( "E200008", { 'URL' => $product2URL, 'POINT' => 'ProductName' } );
						next;
					}
					if(!$productId){
						Log::Write::setLog( "E200008", { 'URL' => $product2URL, 'POINT' => 'ProductId' } );
						next;
					}
					my $product = {
						'ProductId'  => $productId,
						'ProductURL' => $productURL,
						'Name'       => $productName,
						'Category'   => [ { 'Part' => \@cats } ],
					};
					push @tempArray, $product;
				}
			}
			Log::Write::setLog( 'A200001', { 'COUNT' => scalar(@tempArray), 'URL'=>$url } );
			push @allProducts, @tempArray;
		} 
	}
	# A200003 The total count of the entryUrl obtained
	Log::Write::setLog( 'A200003', { 'COUNT' => scalar(@allProducts) } );
	return @allProducts;
}

	


1;